package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	@Autowired
	private WxMaService wxMaService;
	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;
	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;

	@Override
	public void updateUser(UserInfoVo userInfoVo, Long userId) {
		//创建对象
		UserInfo userInfo = new UserInfo();
		//属性拷贝
		BeanUtils.copyProperties(userInfoVo,userInfo);
		userInfo.setId(userId);
		updateById(userInfo);
	}

	@Override
	public UserInfoVo getUserInfo(Long userId) {
		//	创建对象
		UserInfoVo userInfoVo = new UserInfoVo();
		//	查询用户对象
		UserInfo userInfo = this.getById(userId);
		//	属性拷贝：
		BeanUtils.copyProperties(userInfo, userInfoVo);
		return userInfoVo;
	}

	@Override
	public Map<String, Object> wxLogin(String code) {
		//	创建map 集合
		HashMap<String, Object> map = new HashMap<>();
		WxMaJscode2SessionResult wxMaJscode2SessionResult=null;
        try {
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
		String openid = wxMaJscode2SessionResult.getOpenid();
		UserInfo userInfo= userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
		if (userInfo==null){
			//没有注册
			userInfo = new UserInfo();
			//赋值
			userInfo.setWxOpenId(openid);
			userInfo.setNickname("听友"+System.currentTimeMillis());
			userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
			userInfoMapper.insert(userInfo);
			//给钱
			rabbitService.sendMessage(MqConst.EXCHANGE_USER,MqConst.ROUTING_USER_REGISTER,userInfo.getId());
		}
		//创建token
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		//保存信息进缓存
		String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
		redisTemplate.opsForValue().set(loginKey,userInfo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
		//存储
		map.put("token",token);
		//返回数据
		return map;

	}

	@Override
	public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> trackIdList, Long userId) {
		//创建map集合
		HashMap<Long, Integer> map = new HashMap<>();
		//	1.	判断用户是否购买过专辑 user_paid_album
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userId).eq(UserPaidAlbum::getAlbumId, albumId));
		//判断
		if (null!=userPaidAlbum){
			//购买了专辑,当前所有的声音都应该免费;trackId:1
			return trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
		}else {
			//	判断用户是否购买过声音！ user_paid_track
			//	用户购买过的声音Id 集合列表
			List<Long> userPaidTrackIdlist = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());

			//判断
			for (Long trackId : trackIdList) {
				//	判断userPaidTrackIdlist这个集合中是否包含trackId;
				if (userPaidTrackIdlist.contains(trackId)){
					//	说明这个 声音Id 已购买：
					map.put(trackId,1);
				}else {
					//	说明这个 声音Id 未购买：
					map.put(trackId,0);
				}
			}
		}
		return map;
	}
}
